package com.hrm.util;

import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;

import com.hrm.entity.Role;
/**
 * @author zhuchaoqiang
 */
@SuppressWarnings("all")
public class MyObject implements Serializable,JSONAware{

	private static final long serialVersionUID = 1L;

	public String getMyName() {
		String name = this.getClass().getSimpleName();
		return name;
	}
	@Override
	public String toString() {
		Object obj = this;
		Class class1 = obj.getClass();
		Field[] fields = class1.getDeclaredFields();
		StringBuffer sbf = new StringBuffer();
		sbf.append("\n" + class1.getName() + "\n");
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				Object object = field.get(obj);
				if(!"".equals(field.getName())){
					sbf.append("[" + field.getName() + "="
							+ field.get(obj) + "]\n");
				}
			} catch (Exception e) {
				System.out.println("获取" + class1.getName() + "属性和属性值出错!");
				e.printStackTrace();
			}
		}
		return sbf.toString();
	}
	
	public String toJSONString(){
		StringWriter out = new StringWriter();
		JSONObject jo = new JSONObject();
		Object obj = this;
		Class class1 = obj.getClass();
		Field[] fields = class1.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				if("java.util.Date".equals(field.getType().getName())){//时间格式json-simple无法转换，所以讲时间格式转成String输出
					jo.put(field.getName(), field.get(obj)==null?"":field.get(obj).toString());
				}else{
					jo.put(field.getName(), field.get(obj)==null?"":field.get(obj));
				}
			} catch (Exception e) {
				System.err.println("获取" + class1.getName() + "属性和属性值出错!");
				e.printStackTrace();
			}
		}
       try {
			jo.writeJSONString(out);
		} catch (IOException e) {
			System.err.println("转换" + class1.getName() + "为JSON字符串出错!");
			e.printStackTrace();
		}
		return jo.toJSONString();
	}
	public static void main(String[] args){
		Role role = new Role();
		role.setCreateDate(new Date());
		System.out.println(role.toJSONString());
	}

}
